package com.ruoyi.project.flink.latest;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.util.Collector;
import org.apache.kafka.clients.consumer.ConsumerConfig;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Properties;

public class JdbcSinkExample {

    public static void main(String[] args) throws Exception {
        //1.获取环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.创建消费者
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.33.207:9092");
//        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"test");
        FlinkKafkaConsumer<String> kafkaConsumer = new FlinkKafkaConsumer<>("test_2", new SimpleStringSchema(), properties);
        //3.消费者与对应的flink流关联
        DataStreamSource<String> dataStream = env.addSource(kafkaConsumer);
        SingleOutputStreamOperator<Tuple2<String, Integer>> dataSource = dataStream.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {

            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                String[] file = value.split(",");
                for ( String word : file ) {
                    out.collect(new Tuple2<>(word, 1));
                }
            }
        })
                .keyBy(0)
                .sum(1);

        //连接数据库
        dataSource.addSink(new MyJDBCSink());
        dataSource.print();
        //4.执行操作
        env.execute();
    }

    public static class MyJDBCSink extends RichSinkFunction<Tuple2<String,Integer>> {
        //定义sql连接、预编译器
        Connection conn = null;
        PreparedStatement insertStmt = null;
        PreparedStatement updateStmt = null;

        //初始化 、 创建连接 、 和 预编译语句
        @Override
        public void open(Configuration parameters) throws Exception {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8","root","123456");
            insertStmt = conn.prepareStatement("INSERT INTO test_yuluo (word, number) VALUES (?, ?)");
            updateStmt = conn.prepareStatement("UPDATE test_yuluo SET word = ? WHERE number = ? ");
        }

        // 执行更新语句，注意不要留 super
        @Override
        public void invoke(Tuple2<String, Integer> value, Context context) throws Exception {

            updateStmt.setString(1, value.f0);
            updateStmt.setInt(2,value.f1);
            updateStmt.execute();


            // 如果刚才 update 语句没有更新，那么插入
            if ( updateStmt.getUpdateCount() == 0 ) {
                insertStmt.setString(1, value.f0);
                insertStmt.setInt(2,value.f1);
                insertStmt.execute();
            }
        }

        @Override
        public void close() throws Exception {
            insertStmt.close();
            updateStmt.close();
            conn.close();

        }
    }
}
